<template>
  <div class="app-container">

    <!-- 查询和其他操作
    <div class="filter-container">
      <el-input v-model="listQuery.userId" clearable class="filter-item" style="width: 160px;" placeholder="请输入用户ID" />
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 160px;" placeholder="手机号码" />
      <el-input v-model="listQuery.orderSn" clearable class="filter-item" style="width: 160px;" placeholder="请输入订单编号" />
      <el-date-picker v-model="listQuery.timeArray" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" class="filter-item" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" />
      <el-select v-model="listQuery.orderStatusArray" multiple style="width: 200px" class="filter-item" placeholder="请选择订单状态">
        <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value" />
      </el-select>
      <el-button v-permission="['GET /admin/order/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <div class="filter-container">
      <el-input v-model="listQuery.orderSn" clearable class="filter-item" style="width: 160px;" placeholder="请输入订单编号" />
      <el-button v-permission="['GET /admin/order/list']" class="filter-item" type="primary" @click="handleReplacementOrder">补单</el-button>
    </div>-->

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。"
    show-summary
    border fit highlight-current-row>

      <el-table-column align="center" min-width="100" label="户主" prop="name" />


      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['GET /admin/IdentityCard/detail']" type="primary"  @click="handleDetail(scope.row)">成员详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 订单详情对话框 -->
    <el-dialog :visible.sync="orderDialogVisible" title="成员详情" width="1100" >
      <section ref="print" id="print">
        <div style="height: 40px;"></div>
        <el-form label-position="left">
          <p style="font-size: 28px;">罗城仫佬族自治县小长安镇龙腾村农村集体经济组织成员身份认定调查摸底表</p>
          <p style="font-size: 14px;">
            <span>组织单位名称：龙腾村</span>
            <span style="margin-left: 200px;">填表时间：______年______月______日           编号：________________</span>
          </p>
            <el-table :data="orderDetail.listIdentity" border style="width: 100%">
              <el-table-column align="center" label="成员姓名" prop="name" />
              <el-table-column align="center" label="性别" prop="sex" />
              <el-table-column align="center" label="出生年月" prop="birthday"/>
              <el-table-column align="center" label="与户主关系" prop="relation" />
              <el-table-column align="center" label="身份证号码" prop="card" min-width="170%"/>
              <el-table-column align="center" label="户口变动情况">
                <el-table-column align="center" label="户口性质"  />
                <el-table-column align="center" label="迁入时间"  />
                <el-table-column align="center" label="原因"  />
                <el-table-column align="center" label="迁出时间" />
                <el-table-column align="center" label="原因"  />
              </el-table-column>
              <el-table-column align="center" label="是否确认为本集体经济组织成员" >
                <template slot-scope="scope">
                  <span>{{ scope.row.orderStatus==''?'是':'是' }}</span>
                </template>
              </el-table-column>
            </el-table>
            <el-table :data="listIdentity2" border style="width: 100%" :span-method="arraySpanMethod">
              <el-table-column  label="以上调查情况属实，户主签字：" prop="name"/>
              <el-table-column  label="认定小组（签名）："  />
              <el-table-column  label="认定时间："  />
            </el-table>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="printOrder">打 印</el-button>
      </span>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog :visible.sync="shipDialogVisible" title="发货">
      <el-form ref="shipForm" :model="shipForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="快递公司" prop="shipChannel">
          <el-select v-model="shipForm.shipChannel" placeholder="请选择">
            <el-option v-for="item in channels" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递编号" prop="shipSn">
          <el-input v-model="shipForm.shipSn" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip">确定</el-button>
      </div>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog :visible.sync="refundDialogVisible" title="退款">
      <el-form ref="refundForm" :model="refundForm" status-icon label-position="left" label-width="100px" style="width: 400px; height: 800px; margin-left:50px;">
        <el-form-item label="退款金额" prop="refundMoney">
          <el-input type="textarea"   v-model="refundForm.refundMoney"  />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund">确定</el-button>
      </div>
    </el-dialog>

    <!-- 发送消息对话框 -->
    <el-dialog :visible.sync="pushNotification" title="推送消息">
      <el-form ref="pushForm" :model="pushForm" status-icon label-position="left" label-width="auto" style="width: 400px; margin-left:50px;">
        <el-form-item label="消息">
          <el-input  type="text" v-model="pushForm.openId" label-width="auto"  style="width: 600px;" placeholder="用户openId"></el-input>
        </el-form-item>
        <el-form-item label="消息">
          <el-input  type="textarea" :autosize="{ minRows: 6, maxRows: 10}" v-model="pushForm.msg" label-width="auto"  style="width: 600px;" placeholder="默认: 您在平台的订单已派单，请于(17:30 - 18：30)时间段在民大相思湖校区西门领取；其他地区请忽略！"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pushNotification = false">取消</el-button>
        <el-button type="primary" @click="pushGZHmsg">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style media="print">
    @page {
      size: auto;
      margin: 5mm; /* this affects the margin in the printer settings */
    }
</style>
<script>
import { listIdentity, detailIdentity, detailOrder, listOrder, listChannel, refundOrder, deleteOrder, shipOrder, pushGZHmsg, buildOrder, ReplacementOrder } from '@/api/order'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import checkPermission from '@/utils/permission' // 权限判断函数

const statusMap = {
  101: '未付款',
  102: '用户取消',
  103: '系统取消',
  201: '已付款',
  202: '申请退款',
  203: '已退款',
  300: '已接单',
  301: '配送中',
  401: '用户收货',
  402: '系统收货'
}

export default {
  name: 'Order',
  components: { Pagination },
  filters: {
    orderStatusFilter(status) {
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      statusMap,
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        user: {},
        orderGoods: [],
        listIdentity: []
      },
      listIdentity: [],
      listIdentity2: [{}],
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined
      },
      shipDialogVisible: false,
      refundForm: {
        orderId: undefined,
        refundMoney: undefined
      },
      refundDialogVisible: false,
      downloadLoading: false,
      pushNotification: false,
      pushForm: {
        orderSn: undefined,
        openId: undefined,
        msg: undefined,
      },
      channels: []
    }
  },
  mounted() {
    window.getList = this.getList;
  },
  created() {
    this.getList()
    this.getChannel()
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true
      if (this.listQuery.timeArray && this.listQuery.timeArray.length === 2) {
        this.listQuery.start = this.listQuery.timeArray[0]
        this.listQuery.end = this.listQuery.timeArray[1]
      } else {
        this.listQuery.start = null
        this.listQuery.end = null
      }

      listIdentity(this.listQuery).then(response => {
        var list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false

        var lists = []
        for(var i=0;i<list.length;i++){
          var shipChannel = list[i].shipChannel
          if(shipChannel != null){
            list[i].shipChannel = JSON.parse(shipChannel).data
          }
          lists.push(list[i])
        }
        this.list = lists
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },

    getChannel() {
      listChannel().then(response => {
        this.channels = response.data.data
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleReplacementOrder() {
      ReplacementOrder(this.listQuery).then(response => {
        this.$notify.success({
          title: '成功',
          message: '补单成功'
        })
        this.listQuery.orderSn = ''
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handlePush(row){
      this.pushNotification = true
      this.pushForm.orderSn = row.orderSn
    },
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (rowIndex % 2 === 0) {
          if (columnIndex === 0) {
            return [1, 3];
          } else if (columnIndex === 1) {
            return [0, 0];
          }
        }
      },
    handleDetail(row) {
      detailIdentity(row.id).then(response => {
        /*
        let arr = []
        for(let i in response.data.listIdentity){
            arr.push(macTypeList[i])
            }*/
        this.orderDetail = response.data.data

      })
      this.orderDialogVisible = true
    },
    handleShip(row) {
      this.shipForm.orderId = row.id
      this.shipForm.shipChannel = row.shipChannel
      this.shipForm.shipSn = row.shipSn

      this.shipDialogVisible = true
      this.$nextTick(() => {
        this.$refs['shipForm'].clearValidate()
      })
    },
    handleOrder(row){
      buildOrder({ orderId: row.id }).then(response => {
        this.$notify.success({
          title: '成功',
          message: '接单成功'
        })
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    confirmShip() {
      this.$refs['shipForm'].validate((valid) => {
        if (valid) {
          shipOrder(this.shipForm).then(response => {
            this.shipDialogVisible = false
            this.$notify.success({
              title: '成功',
              message: '确认发货成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    handleDelete(row) {
      deleteOrder({ orderId: row.id }).then(response => {
        this.$notify.success({
          title: '成功',
          message: '订单删除成功'
        })
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handleRefund(row) {
      this.refundForm.orderId = row.id
      this.refundForm.refundMoney = row.actualPrice

      this.refundDialogVisible = true
      this.$nextTick(() => {
        this.$refs['refundForm'].clearValidate()
      })
    },
    confirmRefund() {
      this.$refs['refundForm'].validate((valid) => {
        if (valid) {
          refundOrder(this.refundForm).then(response => {
            this.refundDialogVisible = false
            this.$notify.success({
              title: '成功',
              message: '确认退款成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    pushGZHmsg() {
      this.$refs['pushForm'].validate((valid) => {
        if (valid) {
          pushGZHmsg(this.pushForm).then(response => {
            this.pushNotification = false
            this.pushForm.openId = undefined
            this.$notify.success({
              title: '成功',
              message: '推送消息成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      });
      this.pushNotification = false
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['订单ID', '订单编号', '用户ID', '订单状态', '是否删除', '收货人', '收货联系电话', '门店ID', '门店名称']
        const filterVal = ['id', 'orderSn', 'userId', 'orderStatus', 'isDelete', 'consignee', 'mobile', 'shopId', 'shopName']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '订单信息')
        this.downloadLoading = false
      })
    },
    printOrder() {
      this.$print(this.$refs.print)
      this.orderDialogVisible = false
    }
  }
}
</script>
